package io.shdxhl.simplerpc.client.strategy;

import io.shdxhl.simplerpc.code.annotation.SimpleLoadBalance;
import io.shdxhl.simplerpc.code.config.SimpleConfiguration;
import io.shdxhl.simplerpc.code.netty.strategy.LoadBalanceStrategy;
import io.shdxhl.simplerpc.code.netty.strategy.StrategyProvider;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.Objects;

@Slf4j
@Component
public class DefaultStrategyProvider implements StrategyProvider, ApplicationContextAware {

    @Autowired
    private SimpleConfiguration simpleConfiguration;

    private LoadBalanceStrategy loadBalanceStrategy;
    /**
     * 用户配置的信息
     * @return
     */
    @Override
    public LoadBalanceStrategy getStrategy() {
        return loadBalanceStrategy;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        Map<String, Object> beansWithAnnotation = applicationContext.getBeansWithAnnotation(SimpleLoadBalance.class);
        for (Object bean : beansWithAnnotation.values()) {
            SimpleLoadBalance simpleLoadBalance =  bean.getClass().getAnnotation(SimpleLoadBalance.class);
            if(Objects.nonNull(simpleLoadBalance)){
                if(simpleLoadBalance.strategy().equals(simpleConfiguration.getStrategy())){
                    loadBalanceStrategy = (LoadBalanceStrategy) bean;
                    break;
                }
            }
        }
    }
}
